// pages/cart/cart.js
const app = getApp();
import { request, toast } from './../../utils/index.js';
import { tokenExceed } from './../../utils/token.js';
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
import Notify from '../../miniprogram_npm/@vant/weapp/notify/notify.js';
var clicks = 0;
import { version } from '../../utils/config'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    checked: false,
    workFlag: true,
    status: '停止接单',
    messList: '',
    name: '',
    showFlag: false,
    showView: true,
    message: '密码为手机号后六位',
    env: '',
    clicks: '', // 点击次数
  },
  onChange({ detail }) {
    wx.showModal({
      title: '亲爱的用户',
      content: `是否确定要切换接单状态？`,
      success: res => {
        if (res.confirm) {
          //console.log(detail)
          if (detail == true) {
            // 上班
            try {
              const token = wx.getStorageSync('token')
              request({
                url: '/changeWorkState',
                method: 'GET',
                data: {
                  token: token,
                  state: 1
                },
                header: {
                  'content-type': 'application/json',
                  'token': `${token}`
                }
              }).then(res => {
                if(res.data.code == 200) {
                  this.setData({
                    status: '接单',
                    checked: detail
                  });
                  Toast.success('您已接单');
                } else {
                  Notify({
                    message: `${res.data.msg}`,
                    type: 'danger'
                  })
                }
                // toast({ title: '您已上班' })
                //console.log(res)
              })
            } catch (e) {
              //console.error(e)
            }
          } else if (detail == false) {
            // 下班
            try {
              const token = wx.getStorageSync('token')
              request({
                url: '/changeWorkState',
                method: 'GET',
                data: {
                  token: token,
                  state: 0
                },
                header: {
                  'content-type': 'application/json',
                  'token': `${token}`
                }
              }).then(res => {
                if(res.data.code == 200) {
                  this.setData({
                    status: '停止接单',
                    checked: detail
                  });
                  Toast.success('您已停止接单');
                } else {
                  Notify({
                    message: `${res.data.msg}`,
                    type: 'danger'
                  })
                }
                // toast({ title: '您已下班' })
                //console.log(res)
              })
            } catch (e) {
              //console.error(e)
            }
          }
        }
      }
    });
  },
  loginTo() {
    wx.navigateTo({
      url: '../login/login',
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const name = wx.getStorageSync('name')
    const work = wx.getStorageSync('work')
    this.setData({
      name: name
    })
    console.log(work,work)
    if (name !== '') {
      this.message()
      // const iswork = 1
      if(work == 1) {
        this.iswork = true
        // 上班
        try {
          const token = wx.getStorageSync('token')
          request({
            url: '/changeWorkState',
            method: 'GET',
            data: {
              token: token,
              state: work
            },
            header: {
              'content-type': 'application/json',
              'token': `${token}`
            }
          }).then(res => {
            if(res.data.code == 200) {
              this.setData({
                status: '接单',
                checked: true
              });
              Toast.success('您已接单');
            } else {
              Notify({
                message: `${res.data.msg}`,
                type: 'danger'
              })
            }
            // toast({ title: '您已上班' })
            //console.log(res)
          })
        } catch (e) {
          //console.error(e)
        }
      } else if (work == 0) {
        this.iswork = false
        // 下班
        try {
          const token = wx.getStorageSync('token')
          request({
            url: '/changeWorkState',
            method: 'GET',
            data: {
              token: token,
              state: work
            },
            header: {
              'content-type': 'application/json',
              'token': `${token}`
            }
          }).then(res => {
            if(res.data.code == 200) {
              this.setData({
                status: '下班',
                checked: false
              });
              Toast.success('您已下班');
            } else {
              Notify({
                message: `${res.data.msg}`,
                type: 'danger'
              })
            }
          })
        } catch (e) {
          //console.error(e)
        }
      }
    }
  },
  // 配送员配送信息汇总
  message() {
    try {
      const token = wx.getStorageSync('token')
      request({
        url: '/summary',
        method: 'GET',
        data: {
          token: token
        },
        header: {
          'content-type': 'application/json',
          'token': `${token}`
        }
      }).then(res => {
        //console.log(res.data.result)
        if(res.data.code == 200) {
          this.setData({
            messList: res.data.result
          })
        } else {
          Notify({
            message: `${res.data.msg}`,
            type: 'danger'
          })
        }
      })
    } catch (e) {
      //console.error(e)
    }
  },
  // 退出登录
  backLogin: function () {
    const token = wx.getStorageSync('token')
    request({
      url: '/logout',
      data: {
        token: token
      },
      header: {
        'content-type': 'application/json',
        'token': `${token}`
      }
    }).then(res => {
      const code = res.data.code
      if (code === 200) {
        wx.showToast({
          title: '退出登录成功',
          icon: 'success',
          duration: 2000,
          success: function () {
            tokenExceed()
          }
        })
      } else if (code === 50000) {
        toast({ title: 'token已过期,请重新登录!' })
      }
    }).finally(() => {
      tokenExceed()
    })
    // 下班
    try {
      const token = wx.getStorageSync('token')
      request({
        url: '/changeWorkState',
        method: 'GET',
        data: {
          token: token,
          state: 0
        },
        header: {
          'content-type': 'application/json',
          'token': `${token}`
        }
      }).then(res => {
        this.setData({
          status: '下班',
          checked: false
        });
        Toast.success('您已下班');
      })
    } catch (e) {
      //console.error(e)
    }
  }, 
  onClickHide() {
    this.setData({ showFlag: false });
  },
  noop() {
    this.setData({
      message: '111'
    })
  },
  // 重置密码
  toLogin: function () {
    const token = wx.getStorageSync('token')
    const resetname = wx.getStorageSync('resetname')
    const telNo = wx.getStorageSync('pass')
    console.log('00000');
    request({
      url: '/resetPwd', //仅为示例，并非真实的接口地址
      method: 'POST',
      data: {
        resetname,
        telNo
      },
      header: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'token': `${token}`
      }
    }).then(res => {
      console.log(this,'this')
      const code = res.data.code
      if (code === 200) {
        const _this = this
        this.setData({ show: true })
        wx.showToast({
          title: '重置密码成功',
          icon: 'success',
          duration: 2000,
          success: function () {
            clearTimeout(timerData)
            _this.setData({
              // message: telNo,
              showFlag: true
            })
            let timerData = setTimeout(
              function () {
                _this.setData({
                  showFlag: false
                 })
                // console.log('setInterval==' ,'等待2s后再执行');
                wx.navigateTo({
                  url: '../login/login',
                })
              }
            , 2000)
          }
        })
      } else {
        toast({ title: '密码错误' })
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      env: wx.getStorageSync('API_URL').slice(0,1)
    })
    const name = wx.getStorageSync('name')
    const token = wx.getStorageSync('token')
    if (token) {
      this.message()
      this.setData({
        name: name
      })
    } else {
      this.setData({
        name: ''
      })
      tokenExceed()
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  /**
   * 长按事件
   */
  touchStart:function(e){
    var that=this;
    // console.log('touchStart',e)
    that.setData({
      touchStart:e.timeStamp
    })
  },
  /**
   * 长按事件
   */
  touchEnd:function(e){
    var that=this;
    that.setData({
      touchEnd:e.timeStamp
    })
    // console.log('touchEnd',e)
  },
  /**
   * 长按事件
   */
  pressTap:function(){
    var that=this;
    var touchTime=that.data.touchEnd-that.data.touchStart;
    if(touchTime>8000){ //自定义长按时长，单位为ms
      wx.navigateTo({
        url: '../env/env',
      })
    }
  },
  /**
   * 切换环境
   */
  selectEnv(e) {
    const { value, index } = e.detail;
    console.log((`当前值：${value}, 当前索引：${index}`))
    // Toast(`当前值：${value}, 当前索引：${index}`);
    // wx.setStorageSync('API_URL',this.EnvList[e.detail.value].Env)
    //这里应为暂时没找到可以立刻重启所有页面的方法故暂时用这种方法(反正都是测试用也不麻烦)
    // wx.showToast({
    //   icon: 'none',
    //   title: '请手动重启小程序(点击右上方气泡按钮里面的重新进入小程序)',
    //   duration: 5000
    // })
  },
  /**
   * 多次点击事件
    */
  multipleClicks() {
    let disabled = false;
    // this.clicks = this.clicks + 1
    // clicks = clicks + 1;
    clicks++;
    // console.log('clicks',clicks);
    if(clicks>15){ //自定义长按时长，单位为ms
      disabled = true;
    }
    if(disabled) {
      wx.navigateTo({
        url: '../env/env',
      })
      disabled = false;
      clicks = 0;
    }
    // this.clicks
  },
})